/**
 * date:2019/06/10
 * author:Mr.Chung
 * description:layuimini 框架扩展
 * DavidLee 2019/12/24扩展更改
 */

$(function () {
    var lodash = _;
    layui.define(["element", "jquery", "notice", "laytpl", "iziToast"], function (exports) {
        var element = layui.element,
            $ = layui.$,
            notice = layui.notice,
            layer = layui.layer,
            laytpl = layui.laytpl,
            iziToast = layui.iziToast,
            tabSessionName = "layuiminiTabInfo";

        // 判断是否在web容器中打开
        if (!/http(s*):\/\//.test(location.href)) {
            return layer.alert("请先将项目部署至web容器（Apache/Tomcat/Nginx/IIS/等），否则部分数据将无法显示");
        }

        layuimini = new function () {

            //  系统配置
            // @param name
            // @returns {{BgColorDefault: number, urlSuffixDefault: boolean}|*}
            this.config = function (name) {

                var config = {
                    urlHashLocation: true,   // URL地址hash定位
                    urlSuffixDefault: true,  // URL后缀
                    BgColorDefault: 0,       // 默认皮肤（0开始）
                    checkUrlDefault: false   // 是否判断URL有效
                };

                if (name === undefined) {
                    return config;
                } else {
                    return config[name];
                }
            };

            this.nodetype = function () {
                return { //与后台systemmoduleentity关于系统菜单的类型定义一致
                    toproot: 1,
                    topnavimenu: 2,
                    leftnavimenu: 3,
                    modulepage: 4
                };
            };

            /**
             * 初始化
             */
            this.init = function () {
                layuimini.initBgColor();
                layuimini.initDevice();
                layuimini.initLogo();
                layuimini.initToolgroup();
                layuimini.initHome();
                NProgress.start();
                httpapi.fetchGet('/api/backend/loadsystemmenu').then(res => {
                    NProgress.done();
                    if (!httpapi.checkResponse(res)) {
                        notice.error(res.message);
                    } else {
                        layuimini.initMenu(res.data);
                        layuimini.initTab();
                    }
                }).catch(err => {
                    //notice.error("对不起，获取系统菜单出现未知错误，请您联系系统管理员！");
                    console.log('parsing failed', err);
                });
            };

            /**
             * 初始化设备端
             */
            this.initDevice = function () {
                if (layuimini.checkMobile()) {
                    $('.layuimini-tool i').attr('data-side-fold', 0);
                    $('.layuimini-tool i').attr('class', 'fa fa-indent');
                    $('.layui-layout-body').attr('class', 'layui-layout-body layuimini-mini');
                }
            };

            // 初始化首页信息
            // @param data
            this.initHome = function () {
                const homeurl = '/backendhome.html';
                sessionStorage.setItem('layuiminiHomeHref', homeurl);
                $('#layuiminiHomeTabId').html('<i class="layui-icon layui-icon-home"></i> <span>后台首页</span>');
                $('#layuiminiHomeTabId').attr('lay-id', 'homeurl');
                $('#layuiminiHomeTabIframe').html('<iframe width="100%" height="100%" frameborder="0"  src="' + homeurl + '"></iframe>');
            };

            //初始化logo信息
            //@param data
            this.initLogo = function () {
                var html = '<a href="javascript:;">\n' +
                    '<img src="images/face.jpg" alt="logo">\n' +
                    '<h1>Nowablog</h1>\n' +
                    '</a>';
                $('.layui-layout-admin .layui-logo').html(html);
            };

            this.initToolgroup = function () {
                /**
                * 监听提示信息
                */
                var openTips, headerHeight;
                $("body").on("mouseenter", ".toolgroup", function () {
                    var tips = $(this).data('tips');
                    openTips = layer.tips(tips, $(this), { tips: [2, '#2f4056'], time: 30000 });
                });
                $("body").on("mouseleave", ".toolgroup", function () {
                    try {
                        layer.close(openTips);
                    } catch (e) {
                        console.log(e.message);
                    }
                });
                var toolgrp = {
                    refresh: function () {
                        $(".layui-tab-item.layui-show").find("iframe")[0].contentWindow.location.reload();
                        notice.success('刷新成功');                       
                    },
                    clear: function () {
                        var loading = layer.load(0, { shade: false, time: 2000 });
                        sessionStorage.clear();
                        // 判断是否清理服务端
                        var clearUrl = $(this).attr('data-href');
                        if (typeof clearUrl !== "undefined" && clearUrl !== '' && clearUrl !== null) {
                            getData(clearUrl).then(res => {
                                if (!checkServerResponse(res)) {
                                    notice.error(res.message);
                                } else {
                                    layer.close(loading);
                                    notice.success("服务器端缓存清理成功！");
                                }
                            }).catch(err => {
                                notice.error("对不起，请求服务器缓存清理出现未知错误，请您联系系统管理员！");
                                console.log('parsing failed', err);
                            });
                        } else {
                            layer.close(loading);
                            notice.success("缓存清理成功！");
                        } 
                    },
                    pin: function () {
                        headerHeight = $(".layui-header").height();
                        $(".layui-header").animate({ height: 'toggle' }, "slow", function () {
                            layer.tips("恢复顶部显示可在此处操作", $('.tabMoreOper'), { tips: [3, '#2f4056'], time: 3000 });
                            $('.closeBox .showHeader').removeClass('layui-hide');
                        });
                        $(".layui-side").animate({ top: 0 });
                        $(".layui-body").animate({ top: 0 });
                    },
                    fullscreen: function () {
                        //进入全屏
                        function requestFullScreen() {
                            var el = document.documentElement;
                            var rfs = el.requestFullScreen
                                || el.webkitRequestFullScreen
                                || el.mozRequestFullScreen
                                || el.msRequestFullscreen;
                            if (typeof rfs !== "undefined" && rfs) rfs.call(el);
                            return;
                        }
                        //退出全屏
                        function exitFullScreen() {
                            if (document.exitFullscreen) document.exitFullscreen();
                            else if (document.mozCancelFullScreen) 
                                document.mozCancelFullScreen();
                            else if (document.webkitCancelFullScreen) 
                                document.webkitCancelFullScreen();
                            else if (document.msExitFullscreen) 
                                document.msExitFullscreen();
                        }
                        if ($(this).find('i').hasClass("fa-arrows-alt")) {
                            $(this).data('tips', "退出全屏");
                            $(this).find('i').removeClass('fa-arrows-alt').addClass('fa-compress');
                            requestFullScreen();
                        } else {
                            $(this).data('tips', "全屏");
                            $(this).find('i').removeClass('fa-compress').addClass('fa-arrows-alt');
                            exitFullScreen();
                        }
                    }
                };

                $('.closeBox .showHeader').click(function () {
                    $(".layui-side").animate({ top: headerHeight });
                    $(".layui-body").animate({ top: headerHeight });
                    $(".layui-header").animate({ height: 'toggle' }, "slow", function () {
                        $('.closeBox .showHeader').addClass('layui-hide');
                    });
                    
                });
                $(document).delegate('.layui-nav-item .toolgroup', 'click', function (event) {
                    var type = $(this).data('type');
                    toolgrp[type] ? toolgrp[type].call(this) : ''; 
                    event.stopPropagation();
                });

                $('.login-out').on("click", function () {
                    httpapi.fetchPost('/api/backend/logout').then(res => {
                        if (!httpapi.checkResponse(res)) {
                            notice.error(res.message);
                        } else {//Success
                            iziToast.loading(res.message);
                            $.wait(2000).then(function () {
                                Util.redirect("/backend/login");
                            });
                        }
                    })
                    .catch(error => notice.error("对不起，出现未知错误，请您联系系统管理员！"));
                });
            };

            // 初始化背景色
            this.initBgColor = function () {
                var bgcolorId = sessionStorage.getItem('layuiminiBgcolorId');
                if (bgcolorId === null || bgcolorId === undefined || bgcolorId === '') {
                    bgcolorId = layuimini.config('BgColorDefault');
                }
                var bgcolorData = layuimini.bgColorConfig(bgcolorId),
                    styleTpl = $("#layuiminibgcolor-tpl").html();
                laytpl(styleTpl).render(bgcolorData, function (html) {
                    $('#layuimini-bg-color').html(html);
                });
            };

            //  初始化菜单栏
            //  @param data
            this.initMenu = function (data) {
                var headerMenuHtml = '',
                    headerMobileMenuHtml = '',
                    leftMenuHtml = '',
                    headerMenuCheckDefault = 'layui-this',
                    leftMenuCheckDefault = 'layui-this';
                $.each(data, function (index, node) {
                    headerMenuHtml += '<li class="layui-nav-item ' + headerMenuCheckDefault + '" id="HeaderNavNode_' + node.NodeId + '" data-menu="LeftNavNode_' + node.NodeId + '"> <a href="javascript:;"><i class="' + node.IconCssClass + '"></i> ' + node.Title + '</a> </li>\n';
                    headerMobileMenuHtml += '<dd><a href="javascript:;" id="HeaderNavNode_' + node.NodeId + '" data-menu="LeftNavNode_' + node.NodeId + '"><i class="' + node.IconCssClass + '"></i> ' + node.Title + '</a></dd>\n';
                    leftMenuHtml += '<ul class="layui-nav layui-nav-tree layui-nav-side ' + leftMenuCheckDefault + '" id="LeftNavNode_' + node.NodeId + '">\n';
                    var menuList = node.ChildNodes;
                    $.each(menuList, function (index, menu) {
                        leftMenuHtml += '<li class="layui-nav-item leftmenuitem">\n';
                        if (menu.ChildNodes !== undefined && menu.ChildNodes !== null) {
                            leftMenuHtml += '<a href="javascript:;" class="layui-menu-tips" ><i class="' + menu.IconCssClass + '"></i><span class="layui-left-nav"> ' + menu.Title + '</span> </a>';
                            var buildChildHtml = function (html, child) {
                                html += '<dl class="layui-nav-child">\n';
                                $.each(child, function (childIndex, childMenu) {
                                    html += '<dd>\n';
                                    if (childMenu.ChildNodes !== undefined && childMenu.ChildNodes !== null) {
                                        html += '<a href="javascript:;" class="layui-menu-tips" ><i class="' + childMenu.IconCssClass + '"></i><span class="layui-left-nav"> ' + childMenu.Title + '</span></a>';
                                        html = buildChildHtml(html, childMenu.ChildNodes);
                                    } else {
                                        if (childMenu.Url.length > 0) childMenu.Url = lodash.trimEnd(childMenu.Url, "/");
                                        html += '<a href="javascript:;" class="layui-menu-tips" data-type="tabAdd"  data-tab-mpi="m-p-i-' + childMenu.NodeId + '" data-tab="' + childMenu.Url + '" target="' + (childMenu.Target ? "_blank" : "_self") + '"><i class="' + childMenu.IconCssClass + '"></i><span class="layui-left-nav"> ' + childMenu.Title + '</span></a>\n';
                                    }
                                    html += '</dd>\n';
                                });
                                html += '</dl>\n';
                                return html;
                            };
                            leftMenuHtml = buildChildHtml(leftMenuHtml, menu.ChildNodes);
                        } else {
                            if (menu.Url.length > 0)
                                menu.Url = lodash.trimEnd(menu.Url, "/");
                            leftMenuHtml += '<a href="javascript:;" class="layui-menu-tips"  data-type="tabAdd" data-tab-mpi="m-p-i-' + menu.NodeId + '" data-tab="' + menu.Url + '" target="' + (menu.Target ? "_blank" : "_self") + '"><i class="' + menu.IconCssClass + '"></i><span class="layui-left-nav"> ' + menu.Title + '</span></a>\n';
                        }
                        leftMenuHtml += '</li>\n';
                    });
                    leftMenuHtml += '</ul>\n';
                    headerMenuCheckDefault = '';
                    leftMenuCheckDefault = 'layui-hide';
                });
                $('.layui-header-pc-menu').html(headerMenuHtml); //电脑
                $('.layui-header-mini-menu').html(headerMobileMenuHtml); //手机
                $('.layui-left-menu').html(leftMenuHtml);
                element.render('nav');
            };

            // 初始化选项卡
            this.initTab = function () {
                var locationHref = window.location.href;
                var urlArr = locationHref.split("#");
                var href = "";
                if (urlArr.length >= 2) {
                    href = urlArr.pop();

                    // 判断tab是否存在
                    var checkTab = layuimini.checkTab(href);
                    if (!checkTab) {
                        var title = href,
                            tabId = href,
                            checkHref = "";
                        $("[data-tab]").each(function () {
                            checkHref = $(this).attr("data-tab");

                            // 判断是否带参数了
                            if (layuimini.config('urlSuffixDefault')) {
                                if (href.indexOf("mpi=") > -1) {
                                    var menuParameId = $(this).attr('data-tab-mpi');
                                    if (checkHref.indexOf("?") > -1) {
                                        checkHref = checkHref + '&mpi=' + menuParameId;
                                    } else {
                                        checkHref = checkHref + '?mpi=' + menuParameId;
                                    }
                                }
                            }

                            if (checkHref === tabId) {
                                title = $(this).html();
                                title = title.replace('style="display: none;"', '');

                                // 自动展开菜单栏
                                var addMenuClass = function ($element, level) {
                                    var moduleId = "",
                                        nodeId = "",
                                        tagName = $element.tagNameLowerCase();
                                    if (level === 1) $element.addClass("layui-this");
                                    if (tagName === "li") { //递归结束
                                        if (!$element.hasClass('layui-this')) $element.addClass('layui-nav-itemed');
                                        moduleId = $element.parent().attr('id');
                                        nodeId = lodash.trimStart(moduleId, "LeftNavNode_");
                                        $("li[id^='HeaderNavNode_']").removeClass('layui-this');
                                        $("#HeaderNavNode_" + nodeId).addClass("layui-this");
                                        $(".layui-nav-side").removeClass('layui-this').addClass('layui-hide');
                                        $("#" + moduleId).removeClass('layui-hide').addClass('layui-this'); 
                                        return;
                                    }
                                    if (tagName === "dd" && level > 1)
                                        $element.addClass('layui-nav-itemed');                                    
                                    addMenuClass($element.parent(), ++level);
                                };
                                addMenuClass($(this).parent(), 1);
                            }
                        });
                        var layuiminiHomeTab = $('#layuiminiHomeTab').attr('lay-id'),
                            layuiminiHomeHref = sessionStorage.getItem('layuiminiHomeHref');

                        // 非菜单打开的tab窗口
                        if (href === title) {
                            var layuiminiTabInfo = JSON.parse(sessionStorage.getItem(tabSessionName));
                            if (layuiminiTabInfo !== null) {
                                var check = layuiminiTabInfo[tabId];
                                if (check !== undefined || check !== null) {
                                    title = check['title'];
                                }
                            }
                        }

                        if (layuiminiHomeTab !== href && layuiminiHomeHref !== href) {
                            NProgress.start();
                            $.wait(2000).then(function () {
                                layuimini.addTab(tabId, href, title, true);
                                layuimini.changeTab(tabId);
                                NProgress.done();
                            });
                        }
                    }
                }
                if (layuimini.config('urlHashLocation')) {
                    layuimini.hashTab();
                }
            };

            //  配色方案配置项(默认选中第一个方案)
            //  @param bgcolorId
            this.bgColorConfig = function (bgcolorId) {
                var bgColorConfig = [
                    {
                        headerRight: '#ffffff',
                        headerRightThis: '#ffffff',
                        headerLogo: '#324157',
                        headerFontColor: '#495060',
                        headerFontColorThis: '#409eff',
                        menuLeft: '#324157',
                        menuLeftThis: '#1aa094',
                        menuLeftHover: '#3b3f4b'
                    },
                    {
                        headerRight: '#23262e',
                        headerRightThis: '#0c0c0c',
                        headerLogo: '#0c0c0c',
                        headerFontColor: '#fff',
                        headerFontColorThis: '#fff',
                        menuLeft: '#23262e',
                        menuLeftThis: '#1aa094',
                        menuLeftHover: '#3b3f4b'
                    },
                    {
                        headerRight: '#ffa4d1',
                        headerRightThis: '#bf7b9d',
                        headerLogo: '#e694bd',
                        headerFontColor: '#fff',
                        headerFontColorThis: '#fff',
                        menuLeft: '#1f1f1f',
                        menuLeftThis: '#ffa4d1',
                        menuLeftHover: '#1f1f1f'
                    },
                    {
                        headerRight: '#1aa094',
                        headerRightThis: '#197971',
                        headerLogo: '#0c0c0c',
                        headerFontColor: '#fff',
                        headerFontColorThis: '#fff',
                        menuLeft: '#23262e',
                        menuLeftThis: '#1aa094',
                        menuLeftHover: '#3b3f4b'
                    },
                    {
                        headerRight: '#1e9fff',
                        headerRightThis: '#0069b7',
                        headerLogo: '#0c0c0c',
                        headerFontColor: '#fff',
                        headerFontColorThis: '#fff',
                        menuLeft: '#1f1f1f',
                        menuLeftThis: '#1aa094',
                        menuLeftHover: '#3b3f4b'
                    },

                    {
                        headerRight: '#ffb800',
                        headerRightThis: '#d09600',
                        headerLogo: '#243346',
                        headerFontColor: '#fff',
                        headerFontColorThis: '#fff',
                        menuLeft: '#2f4056',
                        menuLeftThis: '#1aa094',
                        menuLeftHover: '#3b3f4b'
                    },
                    {
                        headerRight: '#e82121',
                        headerRightThis: '#ae1919',
                        headerLogo: '#0c0c0c',
                        headerFontColor: '#fff',
                        headerFontColorThis: '#fff',
                        menuLeft: '#1f1f1f',
                        menuLeftThis: '#1aa094',
                        menuLeftHover: '#3b3f4b'
                    },
                    {
                        headerRight: '#963885',
                        headerRightThis: '#772c6a',
                        headerLogo: '#243346',
                        headerFontColor: '#fff',
                        headerFontColorThis: '#fff',
                        menuLeft: '#2f4056',
                        menuLeftThis: '#1aa094',
                        menuLeftHover: '#3b3f4b'
                    },
                    {
                        headerRight: '#1e9fff',
                        headerRightThis: '#0069b7',
                        headerLogo: '#0069b7',
                        headerFontColor: '#fff',
                        headerFontColorThis: '#fff',
                        menuLeft: '#1f1f1f',
                        menuLeftThis: '#1aa094',
                        menuLeftHover: '#3b3f4b'
                    },
                    {
                        headerRight: '#ffb800',
                        headerRightThis: '#d09600',
                        headerLogo: '#d09600',
                        headerFontColor: '#fff',
                        headerFontColorThis: '#fff',
                        menuLeft: '#2f4056',
                        menuLeftThis: '#1aa094',
                        menuLeftHover: '#3b3f4b'
                    },
                    {
                        headerRight: '#e82121',
                        headerRightThis: '#ae1919',
                        headerLogo: '#d91f1f',
                        headerFontColor: '#fff',
                        headerFontColorThis: '#fff',
                        menuLeft: '#1f1f1f',
                        menuLeftThis: '#1aa094',
                        menuLeftHover: '#3b3f4b'
                    },
                    {
                        headerRight: '#963885',
                        headerRightThis: '#772c6a',
                        headerLogo: '#772c6a',
                        headerFontColor: '#fff',
                        headerFontColorThis: '#fff',
                        menuLeft: '#2f4056',
                        menuLeftThis: '#1aa094',
                        menuLeftHover: '#3b3f4b'
                    }
                ];

                if (bgcolorId === undefined) {
                    return bgColorConfig;
                } else {
                    return bgColorConfig[bgcolorId];
                }
            };

            //  构建背景颜色选择
            //  @returns {string}
             
            this.buildBgColorHtml = function () {
                var html = '';
                var bgcolorId = sessionStorage.getItem('layuiminiBgcolorId');
                if (bgcolorId === null || bgcolorId === undefined || bgcolorId === '') {
                    bgcolorId = 0;
                }
                var bgColorConfig = layuimini.bgColorConfig();
                $.each(bgColorConfig, function (key, val) {
                    if (key === bgcolorId) {
                        html += '<li class="layui-this" data-select-bgcolor="' + key + '">\n';
                    } else {
                        html += '<li  data-select-bgcolor="' + key + '">\n';
                    }
                    html += '<a href="javascript:;" data-skin="skin-blue" style="" class="clearfix full-opacity-hover">\n' +
                        '<div><span style="display:block; width: 20%; float: left; height: 12px; background: ' + val.headerLogo + ';"></span><span style="display:block; width: 80%; float: left; height: 12px; background: ' + val.headerRight + ';"></span></div>\n' +
                        '<div><span style="display:block; width: 20%; float: left; height: 40px; background: ' + val.menuLeft + ';"></span><span style="display:block; width: 80%; float: left; height: 40px; background: #f4f5f7;"></span></div>\n' +
                        '</a>\n' +
                        '</li>';
                });
                return html;
            };

            // DavidLee增加后台首页快捷导航按钮，与左侧后台配置菜单url对应进行重复检查避免同功能窗口多开
            //  判断窗口是否已打开
            //  @param tabId
            this.checkTab = function (tabId, isIframe) {
                // 判断选项卡上是否有
                var checkTab = false,
                    checkTabId = "";
                let lodash = _;
                if (tabId.indexOf("?") >= 0)
                    tabId = lodash.split(tabId, "?")[0];
                if (isIframe === undefined || isIframe === false) {
                    $(".layui-tab-title li").each(function () {
                        checkTabId = $(this).attr('lay-id');
                        if (checkTabId.indexOf("?") >= 0)
                            checkTabId = lodash.split(checkTabId, "?")[0];
                        if (checkTabId !== null && checkTabId === tabId) {
                            checkTab = true;
                        }
                    });
                } else {
                    parent.layui.$(".layui-tab-title li").each(function () {
                        checkTabId = $(this).attr('lay-id');
                        if (checkTabId.indexOf("?") >= 0)
                            checkTabId = lodash.split(checkTabId, "?")[0];
                        if (checkTabId !== null && checkTabId === tabId) {
                            checkTab = true;
                        }
                    });
                }
                if (checkTab === false) {
                    return false;
                }

                // 判断sessionStorage是否有
                var layuiminiTabInfo = JSON.parse(sessionStorage.getItem(tabSessionName));
                if (layuiminiTabInfo === null) {
                    layuiminiTabInfo = [];
                }
                //layuiminiTabInfo数组格式如下
                //layuiminiTabInfo[tabId] = { href: href, title: title };
                //DavidLee 改变已打开tab检测判断，适应iframe窗口快捷方式打开，避免重复打开相同功能tab
                var check = null,
                    storedtabKey = "";
                lodash.forEach(layuiminiTabInfo, function (value, key) {
                    storedtabKey = key;
                    if (key.indexOf("?") >= 0)
                        storedtabKey = lodash.split(key, "?")[0];
                    if (storedtabKey === tabId)
                        check = value;
                });
                //var check = layuiminiTabInfo[tabId];
                if (check === undefined || check === null) {
                    return false;
                }
                return true;
            };

            //  打开新窗口
            //  @param tabId
            //  @param href
            //  @param title
            this.addTab = function (tabId, href, title, addSession) {
                if (addSession === undefined || addSession === true) {
                    var layuiminiTabInfo = JSON.parse(sessionStorage.getItem(tabSessionName));
                    if (layuiminiTabInfo === null) {
                        layuiminiTabInfo = {};
                    }
                    layuiminiTabInfo[tabId] = { href: href, title: title };
                    sessionStorage.setItem(tabSessionName, JSON.stringify(layuiminiTabInfo));
                }
                element.tabAdd('layuiminiTab', {
                    title: title + '<i data-tab-close="" class="layui-icon layui-unselect layui-tab-close">ဆ</i>' //用于演示
                    , content: '<iframe width="100%" height="100%" frameborder="0"  src="' + href + '"></iframe>'
                    , id: tabId
                });
            };

            //  删除窗口
            //  @param tabId
            this.delTab = function (tabId) {
                var layuiminiTabInfo = JSON.parse(sessionStorage.getItem(tabSessionName));
                if (layuiminiTabInfo !== null) {
                    delete layuiminiTabInfo[tabId];
                    sessionStorage.setItem(tabSessionName, JSON.stringify(layuiminiTabInfo));
                }
                element.tabDelete('layuiminiTab', tabId);
            };

            // 切换选项卡
            this.changeTab = function (tabId) {
                element.tabChange('layuiminiTab', tabId);
            };

            // Hash地址的定位
            this.hashTab = function () {
                var layId = location.hash.replace(/^#/, '');
                element.tabChange('layuiminiTab', layId);
                element.on('tab(layuiminiTab)', function (elem) {
                    location.hash = $(this).attr('lay-id');
                });
            };

            // 判断是否为手机
            this.checkMobile = function () {
                var ua = navigator.userAgent.toLocaleLowerCase();
                var pf = navigator.platform.toLocaleLowerCase();
                var isAndroid = (/android/i).test(ua) || (/iPhone|iPod|iPad/i).test(ua) && (/linux/i).test(pf)
                    || /ucweb.*linux/i.test(ua);
                var isIOS = (/iPhone|iPod|iPad/i).test(ua) && !isAndroid;
                var isWinPhone = (/Windows Phone|ZuneWP7/i).test(ua);
                var clientWidth = document.documentElement.clientWidth;
                if (!isAndroid && !isIOS && !isWinPhone && clientWidth > 768) {
                    return false;
                } else {
                    return true;
                }
            };

            //  判断链接是否有效
            //  @param url
            //  @returns {boolean}
            this.checkUrl = function (url) {
                if (!layuimini.config('checkUrlDefault')) {
                    return true;
                }
                var msg = true;
                $.ajax({
                    url: url,
                    type: 'get',
                    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                    async: false,
                    error: function (xhr, textstatus, thrown) {
                        msg = 'Status:' + xhr.status + '，' + xhr.statusText + '，请稍后再试！';
                    }
                });
                return msg;
            };

            //  成功
            //  @param title
            //  @returns {*}
            this.msg_success = function (title) {
                return layer.msg(title, { icon: 1, shade: this.shade, scrollbar: false, time: 2000, shadeClose: true });
            };

            //  失败
            //  @param title
            //  @returns {*}
            this.msg_error = function (title) {
                return layer.msg(title, { icon: 2, shade: this.shade, scrollbar: false, time: 3000, shadeClose: true });
            };

            // 选项卡滚动
            this.tabRoll = function () {
                $(window).on("resize", function (event) {
                    var topTabsBox = $("#top_tabs_box"),
                        topTabsBoxWidth = $("#top_tabs_box").width(),
                        topTabs = $("#top_tabs"),
                        topTabsWidth = $("#top_tabs").width(),
                        tabLi = topTabs.find("li.layui-this"),
                        top_tabs = document.getElementById("top_tabs"),
                        moveEvent = event || window.event;
                    if (top_tabs === null) top_tabs = parent.document.getElementById("top_tabs");
                    //拖动效果
                    var flag = false;
                    var cur = {
                        x: 0,
                        y: 0
                    };
                    var nx, dx, x;
                    function down(event) {
                        flag = true;
                        var touch;
                        if (event.touches) {
                            touch = event.touches[0];
                        } else {
                            touch = event;
                        }
                        cur.x = touch.clientX;
                        dx = top_tabs.offsetLeft;
                    }
                    function move(event) {
                        var self = this;
                        if (flag) {
                            window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
                            var touch;
                            if (event.touches) {
                                touch = event.touches[0];
                            } else {
                                touch = event;
                            }
                            nx = touch.clientX - cur.x;
                            x = dx + nx;
                            if (x > 0) {
                                x = 0;
                            } else {
                                if (x < topTabsBoxWidth - topTabsWidth) {
                                    x = topTabsBoxWidth - topTabsWidth;
                                } else {
                                    x = dx + nx;
                                }
                            }
                            top_tabs.style.left = x + "px";
                            //阻止页面的滑动默认事件
                            document.addEventListener("touchmove", function () {
                                event.preventDefault();
                            }, false);
                        }
                    }
                    //鼠标释放时候的函数
                    function end() {
                        flag = false;
                    }

                    if (topTabsWidth > topTabsBoxWidth) {
                        if (tabLi.position().left > topTabsBoxWidth || tabLi.position().left + topTabsBoxWidth > topTabsWidth) {
                            topTabs.css("left", topTabsBoxWidth - topTabsWidth);
                        } else {
                            topTabs.css("left", -tabLi.position().left);
                        }
                        //pc端拖动效果
                        topTabs.on("mousedown", down(moveEvent));
                        topTabs.on("mousemove", move(moveEvent));
                        $(document).on("mouseup", end);
                        //移动端拖动效果
                        topTabs.on("touchstart", down(moveEvent));
                        topTabs.on("touchmove", move(moveEvent));
                        topTabs.on("touchend", end);
                    } else {
                        //移除pc端拖动效果
                        topTabs.off("mousedown", down(moveEvent));
                        topTabs.off("mousemove", move(moveEvent));
                        topTabs.off("mouseup", end);
                        //移除移动端拖动效果
                        topTabs.off("touchstart", down(moveEvent));
                        topTabs.off("touchmove", move(moveEvent));
                        topTabs.off("touchend", end);
                        topTabs.removeAttr("style");
                        return false;
                    }
                }).resize();
            };
        };

        //  关闭选项卡
        $('body').on('click', '[data-tab-close]', function () {
            NProgress.start();
            $parent = $(this).parent();
            tabId = $parent.attr('lay-id');
            if (tabId !== undefined || tabId !== null) {
                layuimini.delTab(tabId);
            }
            layuimini.tabRoll();
            NProgress.done();
        });

        /**
         * 打开新窗口
         */
        $('body').on('click', '[data-tab]', function () {
            if (typeof NProgress === "undefined")
                NProgress = parent.NProgress;
            var tabId = $(this).attr('data-tab'),
                href = $(this).attr('data-tab'),
                title = $(this).html(),
                target = $(this).attr('target');
            if (target === '_blank') {
                NProgress.done();
                window.open(href, "_blank");
                return false;
            }
            title = title.replace('style="display: none;"', '');

            // 拼接参数
            if (layuimini.config('urlSuffixDefault')) {
                var menuParameId = $(this).attr('data-tab-mpi');
                if (href.indexOf("?") > -1) {
                    href = href + '&mpi=' + menuParameId;
                    tabId = href;
                } else {
                    href = href + '?mpi=' + menuParameId;
                    tabId = href;
                }
            }

            // 判断链接是否有效
            var checkUrl = layuimini.checkUrl(href);
            if (checkUrl !== true) {
                return layuimini.msg_error(checkUrl);
            }

            if (tabId === null || tabId === undefined) {
                tabId = new Date().getTime();
            }
            // 判断该窗口是否已经打开过
            var checkTab = layuimini.checkTab(tabId);
            if (!checkTab) {
                layuimini.addTab(tabId, href, title, true);
            }
            element.tabChange('layuiminiTab', tabId);
            layuimini.initDevice();
            layuimini.tabRoll();
            NProgress.done();
        });

        /**
         * 在iframe子菜单上打开新窗口
         */
        $('body').on('click', '[data-iframe-tab]', function () {
            if (typeof NProgress === "undefined")
                NProgress = parent.NProgress;
            NProgress.start();
            var tabId = $(this).attr('data-iframe-tab'),
                href = $(this).attr('data-iframe-tab'),
                icon = $(this).attr('data-icon'),
                title = $(this).attr('data-title'),
                target = $(this).attr('target');
            if (target === '_blank') {
                NProgress.done();
                window.open(href, "_blank");
                return false;
            }
            title = '<i class="' + icon + '"></i><span class="layui-left-nav"> ' + title + '</span>';
            if (tabId === null || tabId === undefined) {
                tabId = new Date().getTime();
            }
            // 判断该窗口是否已经打开过
            var checkTab = layuimini.checkTab(tabId, true);
            if (!checkTab) {
                var layuiminiTabInfo = JSON.parse(sessionStorage.getItem(tabSessionName));
                if (layuiminiTabInfo === null) {
                    layuiminiTabInfo = {};
                }
                layuiminiTabInfo[tabId] = { href: href, title: title };
                sessionStorage.setItem(tabSessionName, JSON.stringify(layuiminiTabInfo));
                parent.layui.element.tabAdd('layuiminiTab', {
                    title: title + '<i data-tab-close="" class="layui-icon layui-unselect layui-tab-close">ဆ</i>' //用于演示
                    , content: '<iframe width="100%" height="100%" frameborder="0"  src="' + href + '"></iframe>'
                    , id: tabId
                });
            }
            parent.layui.element.tabChange('layuiminiTab', tabId);
            layuimini.tabRoll();
            NProgress.done();
        });

        /**
         * 左侧菜单的切换
         */
        $('body').on('click', '[data-menu]', function () {
            NProgress.start();
            $parent = $(this).parent();
            menuId = $(this).attr('data-menu');
            // header
            $(".layui-header-menu .layui-nav-item.layui-this").removeClass('layui-this');
            $(this).addClass('layui-this');
            // left
            $(".layui-left-menu .layui-nav.layui-nav-tree.layui-this").addClass('layui-hide');
            $(".layui-left-menu .layui-nav.layui-nav-tree.layui-this.layui-hide").removeClass('layui-this');
            $("#" + menuId).removeClass('layui-hide');
            $("#" + menuId).addClass('layui-this');
            NProgress.done();
        });

        /**
         * 选项卡操作
         */
        $('body').on('click', '[data-page-close]', function () {
            var closeType = $(this).attr('data-page-close');
            if (typeof closeType !== "undefined" || closeType !== null) {
                NProgress.start();
                $(".layui-tab-title li").each(function () {
                    tabId = $(this).attr('lay-id');
                    var id = $(this).attr('id');
                    if (id !== 'layuiminiHomeTabId') {
                        var tabClass = $(this).attr('class');
                        if (closeType === 'all') {
                            layuimini.delTab(tabId);
                        } else {
                            if (tabClass !== 'layui-this') {
                                layuimini.delTab(tabId);
                            }
                        }
                    }
                });
                layuimini.tabRoll();
                NProgress.done();
            }
        });

        /**
         * 菜单栏缩放
         */
        $('body').on('click', '[data-side-fold]', function () {
            var $loading = Util.loading(false, 0);
            var isShow = $(this).attr('data-side-fold');
            if (isShow === "1") { // 缩放
                $(this).attr('data-side-fold', 0);
                $('.layuimini-tool i').attr('class', 'fa fa-indent');
                $('.layui-layout-body').attr('class', 'layui-layout-body layuimini-mini');
            } else { // 正常
                $(this).attr('data-side-fold', 1);
                $('.layuimini-tool i').attr('class', 'fa fa-outdent');
                $('.layui-layout-body').attr('class', 'layui-layout-body layuimini-all');
            }
            layuimini.tabRoll();
            element.init();
            $loading.remove();
        });

        /**
         * 弹出配色方案
         */
        $('body').on('click', '[data-bgcolor]', function () {
            var loading = layer.load(0, { shade: false, time: 2 * 1000 });
            var clientHeight = document.documentElement.clientHeight - 95;
            var bgColorHtml = layuimini.buildBgColorHtml();
            var html = '<div class="layuimini-color">\n' +
                '<div class="color-title">\n' +
                '<span>配色方案</span>\n' +
                '</div>\n' +
                '<div class="color-content">\n' +
                '<ul>\n' + bgColorHtml + '</ul>\n' +
                '</div>\n' +
                '</div>';
            layer.open({
                type: 1,
                title: false,
                closeBtn: 0,
                shade: 0.2,
                anim: 2,
                shadeClose: true,
                id: 'layuiminiBgColor',
                area: ['340px', clientHeight + 'px'],
                offset: 'rb',
                content: html,
                end: function () {
                    $('.layuimini-select-bgcolor').removeClass('layui-this');
                }
            });
            layer.close(loading);
        });

        /**
         * 选择配色方案
         */
        $('body').on('click', '[data-select-bgcolor]', function () {
            var bgcolorId = $(this).attr('data-select-bgcolor');
            $('.layuimini-color .color-content ul .layui-this').attr('class', '');
            $(this).attr('class', 'layui-this');
            sessionStorage.setItem('layuiminiBgcolorId', bgcolorId);
            layuimini.initBgColor();
        });

        exports("layuimini", layuimini);
    });
});